const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * 属性列表
   */
  async indexAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 10;
    const name = this.get('name') || '';
    const attribute_category_id = this.get('attribute_category_id');

    const model = this.model('attribute');
    console.log(attribute_category_id);
    let data = null;
    if (attribute_category_id == 0) {
      data = await model.where({name: ['like', `%${name}%`]}).order(['id DESC']).page(page, size).countSelect();
    }
    else {
      data = await model.where({name: ['like', `%${name}%`]}).where({attribute_category_id: attribute_category_id}).order(['id DESC']).page(page, size).countSelect();
    }

    return this.success(data);
  }

  async listAction() {
    const attribute_category_id = this.get('attribute_category_id');
    const model = this.model('attribute');
    const data = await model.where({attribute_category_id: attribute_category_id}).find();

    return this.success(data);
  }

  /**
   *根据id获取属性
   * */
  async infoAction() {
    const id = this.get('id');
    const model = this.model('attribute');
    const data = await model.where({id: id}).find();

    return this.success(data);
  }

  /**
   * 保存物属性**/
  async storeAction() {
    if (!this.isPost) {
      return false;
    }

    const values = this.post();
    const id = this.post('id');

    const model = this.model('attribute');
    if (id > 0) {
      await model.where({id: id}).update(values);
    } else {
      delete values.id;
      await model.add(values);
    }
    return this.success(values);
  }

  /**
   * 删除属性信息**/
  async destoryAction() {
    const id = this.post('id');
    await this.model('attribute').where({id: id}).limit(1).delete();

    return this.success();
  }
};
